


import java.util.Timer;
import java.util.TimerTask;

import tool.KeyboardUtils;

import boot.Boot;



public class SearchKeyHandler {

	private static final int NOT_A_KEY = -1001;
	private static final int TIME_FOR_KEY = 1000;
	int key1 = NOT_A_KEY;
	int key2 = NOT_A_KEY;
	private boolean timer1Expired = false;
	private boolean timer2Expired = false;
	private char letter1;
	private char letter2;
	private static char[] chars = new char[] { 'a', 'd', 'g', 'j', 'm', 'p',
			't', 'w' };
	private int cursorPos = 0;
	private Boot midlet = Boot.getInstance();
	private boolean nowKey2 = false;

	public void processKey(int keyCode) {		
		
		if ((keyCode < 48) || (keyCode > 57)) {
			return;
		}
			
		if ((!nowKey2) &&(key1 == NOT_A_KEY)) {			
			key1 = keyCode;
			setLetter1(getLetter(keyCode));
			new Timer().schedule(new TimerTask() {

				public void run() {
					timer1Expired = true;
					secureCursorMove();
				}
			}, TIME_FOR_KEY);
		} else if ((!nowKey2) && (key1 == keyCode)) {
			if (!timer1Expired) {
				incrementLetter1();
			} else {
				if (key2 == NOT_A_KEY) {
					initKey2(keyCode);
				}
			}
		} else if (key2 == NOT_A_KEY) {
			initKey2(keyCode);
		} else if (key2 == keyCode) {
			if (!timer2Expired) {
				incrementLetter2();
			}
		}
	}

	private void incrementLetter2() {
		setLetter2(getNextLetter(letter2));
	}

	private void initKey2(int keyCode) {
		nowKey2  = true;
		secureCursorMove();
		key2 = keyCode;
		setLetter2(getLetter(keyCode));
		new Timer().schedule(new TimerTask() {

			public void run() {
				timer2Expired = true;
				midlet.searchInputReady(
					new StringBuffer().append(letter1).append(letter2)
						.toString());
			}
		}, TIME_FOR_KEY);
	}

	private void incrementLetter1() {
		setLetter1(getNextLetter(letter1));
	}

	private char getLetter(int keyCode) {
		if (keyCode == 48) {
			return ' ';
		} else if (keyCode == 49) {
			return '1';
		}
		return chars[(keyCode - 50)];
	}

	private void secureCursorMove() {
		if (cursorPos == 0) {						
			midlet.shiftSearchCursor();
		}
	}
	
	private char getNextLetter(char letter) {
		return KeyboardUtils.getNextLetterNoNum(letter);
	}
	
	private void setLetter1(char value) {
		letter1 = value;
		midlet.searchDisplayUpdate(letter1);
	}
	
	private void setLetter2(char value) {
		letter2 = value;
		midlet.searchDisplayUpdate(letter2);
	}
}
